package com.weiqiao.order.service.impl;

import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.mongodb.client.model.Filters;
import com.weiqiao.mall.constant.e.OrderRemarkEnum;
import com.weiqiao.mall.domain.VarietyEntity;
import com.weiqiao.mall.repository.IVarietyRepository;
import com.weiqiao.mall.service.vo.order.OrderUpdateVO;
import com.weiqiao.mall.service.vo.order.OrderVO;
import com.weiqiao.order.domain.OrdersEntity;
import com.weiqiao.order.domain.dto.OrdersEntityDTO;
import com.weiqiao.order.repository.IOrderRepository;
import com.weiqiao.order.service.IOrderService;
import com.weiqiao.utils.DateUtils;
import com.weiqiao.utils.ExportExcelUtils;
import com.weiqiao.utils.SecurityUtils;
import com.weiqiao.utils.StringUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author ChenYF
 * @Description
 * @Date 2020/7/25 15:26
 */
@Service("OrderServiceImpl")
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private IOrderRepository orderRepository;

    @Autowired
    private IVarietyRepository varietyRepository;

    @Override
    public boolean addOrder(Integer company_id, OrdersEntity entity) {
        return orderRepository.addOrder(company_id, new Gson().toJson(entity));
    }

    @Override
    public List<OrdersEntityDTO> getOrderList(OrderVO vo) {
        Integer company_id = SecurityUtils.getCompanyId();
        // 检索条件拼接
        List<OrdersEntityDTO> orderList = new ArrayList<>();
        // 排序条件
        Document sort = new Document("create_date", -1);
        // 分页条件
        int skip = vo.getPage() * vo.getSize();
        List<String> list = orderRepository.getOrderListAndPage(company_id, getParam(vo), sort, skip, vo.getSize());
        if (list != null && list.size() > 0) {
            list.forEach(order -> {
                OrdersEntity entity = new Gson().fromJson(order, OrdersEntity.class);
                // 格式化订单信息
                OrdersEntityDTO dto = formartOrdrList(entity);
                orderList.add(dto);
            });
        }
        return orderList;
    }

    @Override
    public OrdersEntity getOrderDetail(OrderVO vo) {
        Integer company_id = SecurityUtils.getCompanyId();
        OrdersEntity entity = new OrdersEntity();
        String entity_s = orderRepository.getOrderDetail(company_id, getParam(vo));
        if (!StringUtil.isBlank(entity_s)) {
            entity = new Gson().fromJson(entity_s, OrdersEntity.class);
            Date creae_date = DateUtils.currentTimeMillisToDate(entity.getCreate_date());
            entity.setCreate_date(DateUtils.format(creae_date, DateUtils.FORMAT_yyyy_MM_dd_HH_mm_ss));
            entity.getOrderItemList().forEach(order_item -> {
                String show_variety = getShowVariety(order_item.getVariety_id(), order_item.getSecond_variety_id());
                order_item.setShow_variety(show_variety);
            });
        }
        return entity;
    }

    @Override
    public boolean updateOrder(OrderUpdateVO vo) {
        if (StringUtil.isBlank(vo.getOrder_no())) {
            return false;
        }
        String[] orderIds = vo.getOrder_no().split(",");
        Document whereDoc = new Document("order_no", new Document("$in", Arrays.asList(orderIds)));
        Document updateDoc = new Document("company_id", vo.getCompany_id());
        if (!StringUtil.isBlank(vo.getRemark())) {
            updateDoc.append("remark", vo.getRemark());
        }
        if (!StringUtil.isBlank(vo.getState())) {
            updateDoc.append("state", vo.getState());
        }
        return orderRepository.updteOrder(vo.getCompany_id(), whereDoc, updateDoc, true);
    }

    @Override
    public int countNum(OrderVO vo) {
        Integer company_id = SecurityUtils.getCompanyId();
        return orderRepository.countNum(company_id, getParam(vo));
    }

    @Override
    public void pickDownload(OrderVO vo, HttpServletResponse response) {
        Integer company_id = vo.getCompany_id();
        List<OrdersEntity> orderList = new ArrayList();
        String[] idlist = vo.getOrder_no().split(",");
        List<String> list = orderRepository.getOrderList(company_id, new Document("order_no", new Document("$in", Arrays.asList(idlist))));
        list.forEach(s -> {
            OrdersEntity entity = new Gson().fromJson(s, OrdersEntity.class);
            Date creae_date = DateUtils.currentTimeMillisToDate(entity.getCreate_date());
            entity.setCreate_date(DateUtils.format(creae_date, DateUtils.FORMAT_yyyy_MM_dd_HH_mm_ss));
            entity.getOrderItemList().forEach(order_item -> {
                String show_variety = getShowVariety(order_item.getVariety_id(), order_item.getSecond_variety_id());
                order_item.setShow_variety(show_variety);
            });
            orderList.add(entity);
        });
        createExcel(response, orderList, vo.getOrder_type());
    }

    @Override
    public void queryDownload(OrderVO vo, HttpServletResponse response) {
        Integer company_id = vo.getCompany_id();
        List<OrdersEntity> orderList = new ArrayList();
        Bson sort = Filters.eq("create_date", -1);// 排序备用
        List<String> list = orderRepository.getOrderListAndPage(company_id, getParam(vo), sort, vo.getCurpage(), 8000);
        list.forEach(s -> {
            OrdersEntity entity = new Gson().fromJson(s, OrdersEntity.class);
            Date creae_date = DateUtils.currentTimeMillisToDate(entity.getCreate_date());
            entity.setCreate_date(DateUtils.format(creae_date, DateUtils.FORMAT_yyyy_MM_dd_HH_mm_ss));
            entity.getOrderItemList().forEach(order_item -> {
                String show_variety = getShowVariety(order_item.getVariety_id(), order_item.getSecond_variety_id());
                order_item.setShow_variety(show_variety);
            });
            orderList.add(entity);
        });
        createExcel(response, orderList, vo.getOrder_type());
    }

    private Document getParam(OrderVO vo) {
        // 订单类型
        Document doc = new Document("order_type", Integer.parseInt(vo.getOrder_type()));

        // 订单编号
        if (!StringUtils.isBlank(vo.getOrder_no())) {
            doc.append("order_no", vo.getOrder_no());
        }
        // 产品名称
        if (!StringUtils.isBlank(vo.getCommodity_name())) {
            doc.append("orderItemList.commodity_name", new Document("$regex", vo.getCommodity_name()));
        }
        // 客户姓名
        if (!StringUtils.isBlank(vo.getUser_name())) {
            doc.append("user_name", new Document("$regex", vo.getUser_name()));
        }
        // 所属团队
        if (!StringUtils.isBlank(vo.getTeam_name())) {
            doc.append("team_name", new Document("$regex", vo.getTeam_name()));
        }
        // 订单状态
        if (StringUtils.isInteger(vo.getState())) {
            doc.append("state", vo.getState());
        }
        // 产品分类
        if (!StringUtils.isBlank(vo.getVariety_id())) {
            String[] varietyIdList = vo.getVariety_id().split(",");
            doc.append("orderItemList.variety_id", varietyIdList[0]);
            if (varietyIdList.length > 1) doc.append("orderItemList.second_variety_id", varietyIdList[1]);
        }
        // 邀请人
        if (!StringUtils.isBlank(vo.getRecommend_name())) {
            doc.append("recommend_name", new Document("$regex", vo.getRecommend_name()));
        }
        // 创建时间
        String create_time = vo.getCreate_date();
        if (!StringUtil.isBlank(create_time) && create_time.split("~").length > 1) {
            try {
                String start = create_time.split("~")[0];
                String end = create_time.split("~")[1];
                Date startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(start);
                Date endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(end);
                doc.append(
                        "create_date",
                        new Document("$gt", String.valueOf(startDate.getTime()))
                                .append("$lt", String.valueOf(endDate.getTime())));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return doc;
    }

    /**
     * 设置名单其他需要显示内容
     */
    private OrdersEntityDTO formartOrdrList(OrdersEntity entity) {
        OrdersEntityDTO order = new OrdersEntityDTO();
        order.setOrder_no(entity.getOrder_no());
        order.setOrder_type(entity.getOrder_type());
        order.setTeam_name(entity.getTeam_name());
        order.setRecommend_name(entity.getRecommend_name());
        Date creae_date = DateUtils.currentTimeMillisToDate(entity.getCreate_date());
        order.setCreate_date(DateUtils.format(creae_date, DateUtils.FORMAT_yyyy_MM_dd_HH_mm_ss));
        List<OrdersEntity.order_item> items = entity.getOrderItemList(); // 原有商品实体
        List<OrdersEntityDTO.order_item> items_dto = new ArrayList<>(); // 格式化实体
        if (entity.getOrderItemList().size() > 0) {
            // 循环商品信息
            items.forEach(order_item -> {
                String show_variety = getShowVariety(order_item.getVariety_id(), order_item.getSecond_variety_id());
                OrdersEntityDTO.order_item item = new OrdersEntityDTO.order_item();
                item.setCover_url(order_item.getCover_url());
                item.setCommodity_name(order_item.getCommodity_name());
                item.setUser_name(entity.getUser_name());
                item.setPhone(entity.getPhone());
                item.setShow_variety(show_variety);
                item.setState(entity.getState());
                item.setRemark(entity.getRemark());
                item.setVip_price(order_item.getVip_price());
                item.setAccount_number(order_item.getAccount_number());
                item.setNickname(entity.getNickname());
                item.setAmount(order_item.getAmount());
                items_dto.add(item);
            });
            order.setOrderItemList(items_dto);
        }
        return order;
    }

    /**
     * 组装产品分类
     *
     * @param vriety_id         一级分类
     * @param second_variety_id 二级分类
     * @return
     */
    private String getShowVariety(String vriety_id, String second_variety_id) {
        String show_variety;
        String s = varietyRepository.findVarietyFilter(Filters.eq("variety_id", vriety_id));
        if (StringUtils.isBlank(s)) {
            return "";
        }
        VarietyEntity variety = new Gson().fromJson(s, VarietyEntity.class);
        show_variety = variety.getVariety_name();
        if (variety.getSecondVarietyList().size() > 0) {
            for (VarietyEntity.SecondVariety secondVariety : variety.getSecondVarietyList()) {
                if (secondVariety.getSecond_variety_id().equals(second_variety_id)) {
                    show_variety += " - " + secondVariety.getSecond_variety_name();
                }
            }
        }
        return show_variety;
    }

    /**
     * 根据传入数据 导出
     *
     * @param response
     * @param orderlist
     * @throws Exception
     */
    private void createExcel(HttpServletResponse response, List<OrdersEntity> orderlist, String order_type) {
        // 底部标题
        String sheetName = "订单列表";
        boolean bool = "0".equals(order_type);
        // 定义表的列名
        String[] rowsName = bool
                ? new String[]{"订单编号", "产品名称", "手机号码", "客户姓名", "产品分类", "订单状态", "备注", "所属团队", "邀请人", "订单日期"}
                : new String[]{"订单编号", "产品名称", "手机号码", "客户姓名", "产品分类", "订单状态", "备注", "订单日期"};
        // 定义表的内容
        List<Object[]> dataList = new ArrayList<Object[]>();
        Object[] objs = null;
        for (int i = 0; i < orderlist.size(); i++) {
            OrdersEntity order = orderlist.get(i);
            OrdersEntity.order_item item = orderlist.get(i).getOrderItemList().get(0);
            String state = OrderRemarkEnum.OrderRemark.getNameByValue(order.getState());
            objs = new Object[rowsName.length];
            objs[0] = order.getOrder_no();
            objs[1] = item.getCommodity_name();
            objs[2] = order.getPhone();
            objs[3] = order.getUser_name();
            objs[4] = item.getShow_variety();
            objs[5] = state;
            objs[6] = order.getRemark();
            if (bool) {
                objs[7] = order.getTeam_name();
                objs[8] = order.getRecommend_name();
                objs[9] = order.getCreate_date();
            } else {
                objs[7] = order.getCreate_date();
            }
            dataList.add(objs);
        }
        // 创建ExportExcel对象
        ExportExcelUtils ex = new ExportExcelUtils(sheetName, rowsName, dataList);
        // 输出Excel文件
        try {
            OutputStream output = response.getOutputStream();
            ex.export(response, output);
            output.flush();
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
